<template>
  <div class="home-goods">
    <MyPanel :title="category + '商品'" subTitle="精选好物 为您推荐">
      <ul v-if="products.length" class="goods-list">
        <li class="item" v-for="item in products" :key="item.productId">
          <div class="goods-container">
            <!-- 商品图片 -->
            <div class="goods-image">
              <img :src="item.imageUrl" :alt="item.productName" />
            </div>
            
            <!-- 商品名称 -->
            <div class="goods-name ellipsis">{{ item.productName }}</div>
            
            <!-- 价格和购物车按钮 -->
            <div class="goods-price">
              <span class="price">￥{{ item.price }}</span>
              <div class="add-cart-btn" @click="addToCart(item)">
                <span>+</span>
              </div>
            </div>
            
            <!-- 购买按钮 -->
            <div class="buy-btn">
              <button class="purchase-btn" @click="buyNow(item)">立即购买</button>
            </div>
          </div>
        </li>
      </ul>
      
      <!-- 空状态 -->
      <div v-else class="goods-list skeleton-list">
        <div class="no-products">该分类下暂无商品</div>
      </div>
    </MyPanel>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import MyPanel from "@/components/MyPanel.vue";
import { getProductsByCategory, addProductToCart } from '@/api'
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";

export default {
  name: 'CategoryProduct',
  components: {
    MyPanel
  },
  props: {
    category: {
      type: String,
      default: '默认'
    }
  },
  setup(props) {
    const products = ref([])
    const router = useRouter();

    const loadProductsByCategory = async () => {
      try {
        const response = await getProductsByCategory(props.category)
        if (response.code === 200) {
          // 根据后端返回的数据结构提取商品列表
          const productData = response.data || response.result || []
          // 过滤掉status不为1（下架）的商品
          products.value = productData.filter(item => item.status === 1)
        }
      } catch (error) {
        console.error('获取商品失败:', error)
      }
    }

    // 添加商品到购物车
    const addToCart = async (product) => {
      try {
        const res = await addProductToCart({
          productId: product.productId,
          quantity: 1
        });
        
        if (res.code === 200) {
          ElMessage.success('商品已添加到购物车');
        } else {
          ElMessage.error(res.message || '添加购物车失败');
        }
      } catch (error) {
        console.error("添加购物车失败:", error);
        ElMessage.error('添加购物车失败，请稍后重试');
      }
    };
    
    // 立即购买
    const buyNow = async (product) => {
      try {
        // 直接跳转到结算页面，并传递商品信息
        router.push({
          path: '/checkout',
          query: {
            productId: product.productId,
            productName: product.productName,
            price: product.price,
            imageUrl: product.imageUrl,
            quantity: 1
          }
        });
      } catch (error) {
        console.error("立即购买失败:", error);
        ElMessage.error('立即购买失败，请稍后重试');
      }
    };

    onMounted(() => {
      loadProductsByCategory()
    })

    return {
      products,
      addToCart,
      buyNow
    }
  }
}
</script>

<style lang="less" scoped>
@import "@/assets/styles/variables.less";
@import "@/assets/styles/mixins.less";

.home-goods {
  .goods-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    margin-bottom: 40px;
    
    .item {
      width: 265px;
      height: 365px;
      background-color: #f5f5f5;
      margin-bottom: 20px;
      position: relative;
      
      .goods-container {
        padding: 10px;
        text-align: center;
        
        .goods-image {
          width: 100%;
          height: 200px;
          display: flex;
          align-items: center;
          justify-content: center;
          
          img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
          }
        }
        
        .goods-name {
          font-size: 16px;
          margin: 10px 0;
          height: 40px;
          line-height: 20px;
        }
        
        .goods-price {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0 10px;
          margin-bottom: 10px;
          
          .price {
            font-size: 18px;
            color: @priceColor;
            font-weight: bold;
          }
          
          .add-cart-btn {
            width: 30px;
            height: 30px;
            border-radius: 50%;
            background-color: @xtxColor;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            cursor: pointer;
            font-weight: bold;
          }
        }
        
        .buy-btn {
          .purchase-btn {
            width: 90%;
            height: 35px;
            background-color: @xtxColor;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            
            &:hover {
              background-color: #b8884d;
            }
          }
        }
      }
      
      .hoverShadow();
    }
  }
  
  .skeleton-list {
    .no-products {
      width: 100%;
      text-align: center;
      padding: 50px 0;
      color: #999;
    }
  }
}
</style>